from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.views.decorators.csrf import csrf_protect
from .forms import LoginForm, RegisterForm
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import EmailVerifyRecord
from utils.email_send import send_register_email


class MyBackend(ModelBackend):
    """自定义用户验证"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


def active_user(request, active_code):
    all_records = EmailVerifyRecord.objects.filter(code=active_code)
    if all_records:
        for record in all_records:
            email = record.email
            user = User.objects.get(email=email)
            user.is_staff = True
            user.save

    else:
        return HttpResponse('链接无效')
    return redirect('user:login')


# Create your views here.
# @csrf_protect
def login_view(request):
    # if request.method == 'POST':
    #     username = request.POST['username']
    #     password = request.POST['password']
    #     user = authenticate(request, username=username, password=password)
    #     if user is not None:
    #         login(request, user)
    #         return HttpResponse('登录成功')
    #     else:
    #         return HttpResponse('登录失败')

    if request.method != 'POST':
        form = LoginForm()
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            # print(form.cleaned_data)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            print(username, password)
            user = authenticate(request, username=username, password=password)
            print(user)
            if user is not None:
                login(request, user)
                # return HttpResponse('登录成功')
                return redirect('/admin')
            else:
                return HttpResponse('登录失败')
    context = {'form': form}
    return render(request, 'user/login.html', context)


def register(request):
    if request.method != 'POST':
        form = RegisterForm()

    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data['password'])
            new_user.username = form.cleaned_data['email']


            send_register_email(form.cleaned_data['email'], 'register')
            new_user.save()
            return HttpResponse('注册成功')
    context = {'form': form}

    return render(request, 'user/register.html', context)
